package com.baomidou.ant.weChat.service;

import com.baomidou.ant.weChat.config.WxConfig;
import com.baomidou.ant.weChat.model.AccessToken;
import com.baomidou.ant.weChat.model.MessageModel;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * 企业微信发送消息方法
 */
public class SendMessageService {
    //发送消息接口
    private final static String sendMessageUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=";
    //发送消息的类型
    private final static String MSGTYPE = "text";
    //推送消息的应用Id
    private final static String agentId = "1000017";
    //企业应用凭证(此处非实时获取)
    //private final static String TOKEN = "t_p6p9p0bmogqjSnKLXVDRGQu7YKDOsp1BBBdjrNjGaSYEzcJ2hyFiyAdEJCovOma99dwq_hge14K08ZjNCBtW-sEqhJYqFtm7hvysvuh7ovh-zOF1OUHUVm3rAYarUZro4FW5bUpCBkHJLLuNzn653zGXvu0QDKEgu3vFk3j3Mfn0AMetaDqQ1SW3DfgxtA1ys_U2jrgg_ZGuA1KH2lyQ";

    /**
     * 企业接口向下属关注用户发送给微信消息
     * @param messageModel 信息推送实例
     * @return
     */
    public static void sendWeChatMessage(MessageModel messageModel) throws Exception{
        //实时获取TOKEN
        AccessToken accessToken = WxConfig.getAccessTokenTwo();
        String ACCESS_TOKEN = accessToken.getAccess_token();
        //请求串拼接
        String url = sendMessageUrl + ACCESS_TOKEN;
        //封装发送消息请求JSON
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("{");
        stringBuffer.append("\"touser\":" + "\"" + messageModel.getToUser() + "\",");
        stringBuffer.append("\"toparty\":" + "\"" + messageModel.getToParty() + "\",");
        stringBuffer.append("\"totag\":" + "\"" + "@all" + "\",");
        stringBuffer.append("\"msgtype\":" + "\"" + MSGTYPE + "\",");
        stringBuffer.append("\"text\":" + "{");
        stringBuffer.append("\"content\":" + "\"" + messageModel.getContent() + "\"");
        stringBuffer.append("}");
        stringBuffer.append(",\"safe\":" + "\"" + "1" + "\",");
        stringBuffer.append("\"agentid\":" + "\"" + agentId + "\",");
        stringBuffer.append("\"debug\":" + "\"" + "1" + "\"");
        stringBuffer.append("}");
        String json = stringBuffer.toString();
        System.out.println(json);
        try {
            URL postUrl = new URL(url);
            HttpURLConnection http = (HttpURLConnection) postUrl.openConnection();
            http.setRequestMethod("POST");
            http.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            http.setDoOutput(true);
            http.setDoInput(true);
            // 连接超时30秒
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
            // 读取超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000");
            http.connect();
            //写入内容
            OutputStream outputStream = http.getOutputStream();
            outputStream.write(json.getBytes(StandardCharsets.UTF_8));
            InputStream inputStream = http.getInputStream();
            int size = inputStream.available();
            byte[] jsonBytes = new byte[size];
            inputStream.read(jsonBytes);
            String result = new String(jsonBytes, StandardCharsets.UTF_8);
            System.out.println("请求返回结果:" + result);
            //清空输出流
            outputStream.flush();
            //关闭输出通道
            outputStream.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
